package com.yl.immodule.cc

//import com.hm.poc.utils.suspendCancellableCoroutineRefSafe

import android.content.Context
import android.content.Intent
import com.alibaba.android.arouter.launcher.ARouter
import com.android.yl.ylicpsdk.ICPRtcManager
import com.camera.base.R
import com.camera.base.util.YLIMConfig
import com.camera.routemodule.RouterPath
import com.hm.poc.IPocEngineEventHandler
import com.hm.poc.http.data.AudioMeetingInfoResponse
import com.hm.poc.log.ALog
import com.unionbroad.greendao.User
import com.yl.immodule.util.suspendCancellableCoroutineRefSafe
import kotlin.coroutines.resume

/**
 * @author benzly
 * @date 2024/1/13
 */
object CCHelper {

    // 维护会议的全局唯一状态
    data class ConsultationDataModel(
        var owner: Boolean = false,  // 是否会议发起方，需要在业务层记录
        var roomId: String? = null,  // 语音会议房间号
        var audioMeetingSessionId: Long? = null,  // 语音会话sessionId
        var videoMonitorSessionId: Long? = null,  // 视频监控会话sessionId
        val members: ArrayList<User> = ArrayList() // 参会成员
    ) {
        fun clear() {
            ALog.i(TAG, "curCcDataModel clear $this")
            owner = false
            roomId = null
            audioMeetingSessionId = null
            videoMonitorSessionId = null
            members.clear()
        }
    }

    private const val TAG = "CCHelper"
    const val isCcBzMode = false // 会诊模式开关
    val curCcDataModel = ConsultationDataModel()

    /**
     * 用于移动端主动发起发起会诊，其实就是主动发起语音会议
     *
     * 注意：接口回包可能会比sip会议来电更慢
     */
    fun requestConsultation(users: List<User>, callback: IPocEngineEventHandler.Callback<String?>) {
        val icpRtcManager = ICPRtcManager.getsInstance();
        if (!icpRtcManager.hasServiceConnected()) {
            callback.onResponse("会诊发起失败：服务未链接")
            return
        }
        curCcDataModel.members.clear()
        curCcDataModel.members.addAll(users)
        curCcDataModel.owner = true

        val members = users.map { it.number.toString() }
        icpRtcManager.makeAudioMeetingStart(members) {
            ALog.i(TAG, "requestConsultation: result=$it")
            if (it.code != 1 || it.data.isNullOrEmpty()) {
                callback.onResponse("会诊发起失败：$it")
                curCcDataModel.owner = false
                return@makeAudioMeetingStart
            }
            callback.onResponse("会诊发起成功：${it.data}")
            curCcDataModel.roomId = it.data
        }
    }

    fun handlerCCIncoming(context: Context, incomingInfo: IPocEngineEventHandler.IncomingInfo) {
        // 会诊模式: 是语音会议和视频监控结合的
        if (incomingInfo.sessionType == IPocEngineEventHandler.SessionType.TYPE_AUDIO_MEETING ||
            incomingInfo.sessionType == IPocEngineEventHandler.SessionType.TYPE_VIDEO_MONITOR_CALL
        ) {
//            ConsultationActivity.invoke(context, incomingInfo)
        } else {
            if (YLIMConfig.windowManagerChoose) {
//                MeetManger.getInstance().startMeet(
//                    context,
//                    incomingInfo.sessionId,
//                    incomingInfo.callerId,
//                    incomingInfo.callerName,
//                    incomingInfo.sessionType,
//                    incomingInfo.extra,
//                    true
//                )
                ARouter.getInstance()
                    .build(RouterPath.path.av_activity)
                    .withLong("sessionId", incomingInfo.sessionId)
                    .withString("callerId", incomingInfo.callerId)
                    .withString("callerName", incomingInfo.callerName)
                    .withInt("type", incomingInfo.sessionType)
                    .withString("extra", incomingInfo.extra)
                    .withBoolean("isIncomingCall", true)
                    .withFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    .withTransition(R.anim.slide_in_right, R.anim.slide_out_left)
                    .navigation()
            }else{
                ARouter.getInstance()
                    .build(RouterPath.path.av_activity)
                    .withLong("sessionId", incomingInfo.sessionId)
                    .withString("callerId", incomingInfo.callerId)
                    .withString("callerName", incomingInfo.callerName)
                    .withInt("type", incomingInfo.sessionType)
                    .withString("extra", incomingInfo.extra)
                    .withBoolean("isIncomingCall", true)
                    .withFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    .withTransition(R.anim.slide_in_right, R.anim.slide_out_left)
                    .navigation()
//                // 剩余模式: 只会有点对点通话，跳原来的通话界面即可
//                val intent = Intent(context, AvActivity::class.java)
//                intent.putExtra("sessionId", incomingInfo.sessionId)
//                intent.putExtra("callerId", incomingInfo.callerId)
//                intent.putExtra("callerName", incomingInfo.callerName)
//                intent.putExtra("type", incomingInfo.sessionType)
//                intent.putExtra("extra", incomingInfo.extra)
//                intent.putExtra("isIncomingCall", true)
//                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
//                context.startActivity(intent)
            }

        }
    }

    /**
     * 查询当前的会议信息
     */
    suspend fun queryMeetingInfo(roomId: String): AudioMeetingInfoResponse {
        val icpRtcManager = ICPRtcManager.getsInstance();
        return suspendCancellableCoroutineRefSafe {
            icpRtcManager.queryAudioMeetingInfo(roomId) { response ->
                it.continuation?.resume(response)
            }
        }
    }
}